package com.uniontech.curd.controller;

import com.alibaba.fastjson.JSONObject;
import com.uniontech.curd.entity.Users;
import com.uniontech.curd.entity.http.DataResponse;
import com.uniontech.curd.entity.http.Pager;
import com.uniontech.curd.service.CURDService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(value = "/users", name = "用户",method={RequestMethod.POST})
public class UsersController {
    @Autowired
    private CURDService curdService ;

    @RequestMapping(value="/add", name="用户添加")
    public DataResponse add(@RequestBody JSONObject data){
        Integer id = data.getInteger("id");
        String name = data.getString("name");
        Integer age = data.getInteger("age");
        String tel =  data.getString("tel");
        Users users = Users.builder()
                .id(id)
                .name(name)
                .age(age)
                .tel(tel)
                .build();
        boolean isAdd = curdService.addUsers(users);
        DataResponse dr = new DataResponse();
        dr.setData(isAdd);
        return dr;
    }

    @RequestMapping(value="/page", name="用户列表信息")
    public DataResponse page(@RequestParam(value="searchContent", required = false) String searchContent){
        Pager<Users> usersPager = curdService.page(searchContent);
        DataResponse dr = new DataResponse();
        dr.setData(usersPager);
        return dr;
    }

    @RequestMapping(value="/delete", name="删除用户")
    public DataResponse delete(@RequestBody JSONObject data){
        Users users = Users.builder()
                .id(data.getInteger("id"))
                .name(data.getString("name"))
                .age(data.getInteger("age"))
                .tel(data.getString("tel"))
                .build();
        boolean result = curdService.deleteUsers(users);
        Map<String, Object> map = new HashMap<>();
        map.put("result", result);
        DataResponse dr = new DataResponse();
        dr.setData(map);
        return dr;
    }

    @RequestMapping(value="/update", name="更新用户")
    public DataResponse update(@RequestBody JSONObject data){
        Users users = Users.builder()
                .id(data.getInteger("id"))
                .name(data.getString("name"))
                .age(data.getInteger("age"))
                .tel(data.getString("tel"))
                .build();
        boolean result = curdService.updateUsers(users);
        DataResponse dr = new DataResponse();
        dr.setData(result);
        return dr;
    }

}
